<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import {ElForm, ElMessage, ElMessageBox, FormProps, UploadProps} from 'element-plus';

// 定义书籍类型
import type  {Book,BookDetailResponseData,
  BookResponseData,ResponseData} from '@/api/book/type.ts'
import {reqListBook,reqAddBook,reqDeleteBook,reqDeleteBooks} from '@/api/book/index.ts'
import {Delete, Edit, Plus} from "@element-plus/icons-vue";
import { useUserStore } from '@/store/modules/user.ts'
import {useRoute} from "vue-router";
import router from "@/router";

// 获取小仓库，必须要使用大仓库
const userStore = useUserStore()
// 获取用户token，判断用户是否登录，还是未登录
const token = userStore.token


// 表格数据
const bookArr = ref<Book[]>([]);

// 表单数据
const keyword = ref<string>('');

// 分页数据
const pageNo = ref<number>(1);
const pageSize = ref<number>(10);
const total = ref<number>(0);

// 选中的书籍ID
const selectedIds = ref<number[]>([]);

// 获取书籍列表
const getBooks = async () => {
  // 假设从API获取数据
  const result:BookResponseData = await reqListBook(pageNo.value, pageSize.value, keyword.value);
  if(result.code == 200) {
    bookArr.value = result.data.records;
    total.value = result.data.total;
  }
};


// 搜索
const search = () => {
  pageNo.value = 1; // 搜索时重置页码
  getBooks();
};

// 重置
const reset = () => {
  keyword.value = '';
  search();
};

// 选择变化
const selectChange = (selection: Book[]) => {
  selectedIds.value = selection.map(item => item.id as number);
};


// 编辑书籍
const editBook = (book: Book) => {
  Object.assign(addBookForm, {
    id: book.id,
    title: book.title,
    author: book.author,
    publishedYear: book.publishedYear,
    coverUrl: book.coverUrl
  })
  // 实现编辑书籍的逻辑
  addBookDialogVisible.value = true;
};

// 删除书籍
const deleteBook =async (id: number) => {
  // 实现删除书籍的逻辑
  ElMessageBox.confirm('此操作将永久删除该书籍, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    const result: ResponseData = await reqDeleteBook(id);
    if (result.code == 200) {
      ElMessage.success('删除成功');
    } else {
      ElMessage.error('删除失败');
    }
    // 重新获取书籍列表
    getBooks();
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};

// 批量删除书籍
const deleteSelectedBooks = async () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请选择要删除的书籍');
    return;
  }
  ElMessageBox.confirm('此操作将永久删除选中的书籍, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    await reqDeleteBooks(selectedIds.value);
    ElMessage.success('批量删除成功');
    // 重新获取书籍列表
    getBooks();
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};

// 处理分页大小变化
const handleSizeChange = (newSize: number) => {
  pageSize.value = newSize;
  getBooks();
};

// 页面加载时获取书籍数据
onMounted(() => {
  getBooks();
});

// 退出登录
const logout = () => {
  ElMessageBox.confirm('确定要退出登录吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    ElMessage.success('已退出登录');
    // 在此处执行退出登录的逻辑，比如清除用户数据，跳转到登录页面等
    userStore.token = '';
    router.push('/login');
  }).catch(() => {
    ElMessage.info('已取消退出');
  });
};


// 表单数据
const addBookDialogVisible = ref(false);

let addBookForm = reactive<Book>({
  id:null,
  title: '',
  author: '',
  publishedYear: 2024,
  coverUrl: ''
});

const addBookFormRules = {
  title: [{ required: true, message: '请输入书名', trigger: 'blur' }],
  author: [{ required: true, message: '请输入作者', trigger: 'blur' }],
  publishedYear: [{ required: true, message: '请输入出版年份', trigger: 'blur' }],
  coverUrl: [{ required: true, message: '请上传图片', trigger: 'blur' }]
};

// 打开新增书籍对话框
const openAddBookDialog = () => {
  // 清空数据
  Object.assign(addBookForm, {
    id:null,
    title: '',
    author: '',
    publishedYear: 2024,
    coverUrl: ''
  })
  console.log(addBookForm.coverUrl)
  addBookDialogVisible.value = true;
};

// 提交新增书籍表单
const submitAddBookForm = async () => {
  // 判断有没有id, 如果有则更新，没有则新增
  if (addBookForm.id) {
    // 如果有id，则更新书籍信息
    const result: ResponseData = await reqAddBook(addBookForm);
    if (result.code == 200) {
      ElMessage.success('书籍更新成功');
      addBookDialogVisible.value = false;
      getBooks();
    } else {
      ElMessage.error('书籍更新失败');
    }
  } else {
    // 调用新增书籍的API
    const result: ResponseData = await reqAddBook(addBookForm);
    if (result.code == 200) {
      ElMessage.success('书籍添加成功');
      addBookDialogVisible.value = false;
      getBooks();
    } else {
      ElMessage.error('书籍添加失败');
    }
  }

};

const baseApi = import.meta.env.VITE_APP_BASE_API;
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
  addBookForm.coverUrl = response.data.name
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('上传图片只能是 JPG、jpeg格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('文件大小不能超过 2MB!')
    return false
  }
  return true
}



const addBookFormRef =ref(null)

</script>

<template>
  <div>
    <el-header class="header">
      <el-row justify="space-between">
        <el-col>
          <h1>图书管理系统</h1>
        </el-col>
        <el-col>
          <el-button type="primary" @click="logout">退出登录</el-button>
        </el-col>
      </el-row>
    </el-header>

    <el-card style="height: 80px;">
      <el-form :inline="true" class="form">
        <el-form-item label="书名:">
          <el-input placeholder="请输入书名" v-model="keyword"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :disabled="!keyword" @click="search">搜索</el-button>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card style="margin: 10px 0">
      <el-button type="primary" size="default" @click="openAddBookDialog">添加书籍</el-button>
      <el-button type="danger" size="default" @click="deleteSelectedBooks">批量删除</el-button>
      <!-- Table to display books information -->
      <el-table style="margin: 10px 0" border :data="bookArr" @selection-change="selectChange">
        <el-table-column type="selection" align="center"></el-table-column>
        <el-table-column label="#" align="center" type="index"></el-table-column>
        <el-table-column label="ID" align="center" prop="id"></el-table-column>
        <el-table-column label="封面" align="center">
          <template #="{row}">
            <img :src="baseApi + '/' + row.coverUrl" alt="封面" style="width: 50px; height: auto;">
          </template>
        </el-table-column>
        <el-table-column label="书名" align="center" prop="title" show-overflow-tooltip></el-table-column>
        <el-table-column label="作者" align="center" prop="author" show-overflow-tooltip></el-table-column>
        <el-table-column label="出版年份" align="center" prop="publishedYear" show-overflow-tooltip></el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" show-overflow-tooltip></el-table-column>
        <el-table-column label="更新时间" align="center" prop="updateTime" show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" width="300px">
          <template #default="{ row, $index }">
            <el-button type="primary" size="small" :icon="Edit" @click="editBook(row)">编辑</el-button>
            <el-popconfirm :title="`你确定要删除 ${row.title} 吗?`" width="260px" @confirm="deleteBook(row.id)">
              <template #reference>
                <el-button type="danger" size="small" :icon="Delete">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- Pagination -->
      <el-pagination
          v-model:current-page="pageNo"
          v-model:page-size="pageSize"
          :page-sizes="[5, 8, 10, 15]"
          :background="true"
          layout="prev, pager, next, jumper,->,sizes,total"
          :total="total"
          @current-change="getBooks"
          @size-change="handleSizeChange"
      />
    </el-card>

    <!-- 新增书籍对话框 -->
    <el-dialog title="添加书籍" v-model="addBookDialogVisible"    >
      <el-form :model="addBookForm" ref="addBookFormRef" label-width="auto">
        <el-form-item label="书名">
          <el-input v-model="addBookForm.title"></el-input>
        </el-form-item>
        <el-form-item label="作者">
          <el-input v-model="addBookForm.author"></el-input>
        </el-form-item>
        <el-form-item label="出版年份">
          <el-input v-model="addBookForm.publishedYear"></el-input>
        </el-form-item>
        <el-form-item label="封面URL">
          <el-upload
              style="border: #4b4b52 5px"
              action="/api/admin/file/upload"
              class="avatar-uploader"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
          >
            <img v-if="addBookForm.coverUrl" :src="baseApi+'/'+addBookForm.coverUrl" class="avatar" alt="" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addBookDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAddBookForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>


<style scoped lang="scss">
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  background-color: #409EFF;
  color: white;
}

.header h1 {
  margin: 0;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.demo-form-inline .el-input {
  --el-input-width: 220px;
}
</style>

<style>

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
